package com.ql.mangersystem.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ql.mangersystem.common.*;
import com.ql.mangersystem.entity.dto.*;
import com.ql.mangersystem.entity.po.User;
import com.ql.mangersystem.entity.vo.AvatarVo;
import com.ql.mangersystem.entity.vo.LoginVo;
import com.ql.mangersystem.entity.vo.PersonVo;
import com.ql.mangersystem.entity.vo.UserVo;
import com.ql.mangersystem.exception.ServiceException;
import com.ql.mangersystem.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;


@RequestMapping("/user")
@RestController
@Slf4j
@Api("用户端")
@CrossOrigin(value = "http://localhost:5173/")
public class UserController {
    @Resource
    private UserService userService;


    @ApiOperation("登录")
    @AuthAccess
    @PostMapping("/login")
    @HoneyLogs(operation = "用户",type = LogType.LOGIN)
    public Result login(@RequestBody LoginDTO loginDTO) {
        LoginVo vo = userService.login(loginDTO);
        return Result.success(vo);
    }
    @ApiOperation("注册")
    @AuthAccess
    @PostMapping("/register")
    @HoneyLogs(operation = "用户",type = LogType.REGISTER)
    public Result register(@RequestBody RegisterDTO registerDTO) {
//        Integer res = userService.count(registerDTO.getUserAccount());
        Integer result = userService.register(registerDTO);
//        if (res>0){
//            return Result.error("账户已存在");
//        }
        if (result<=0){
            return Result.error("注册失败");
        }
        return Result.success("注册成功");
    }
    @ApiOperation("根据id获取用户信息")
    @GetMapping("/getMessage")
    public Result getMessage(@RequestParam("id") Integer id ) {
        PersonVo vo = userService.getById(id);
        if (vo==null){
            return Result.error("查询失败");
        }
        return Result.success(vo);
    }
    @ApiOperation("根据id获取用户头像")
    @GetMapping("/getAvatar")
    public Result getAvatar(@RequestParam("id") Integer id) {
        AvatarVo vo  = userService.getAvatar(id);
        return Result.success(vo);
    }
    @ApiOperation("修改密码")
    @PostMapping("/changePassword")
    @HoneyLogs(operation = "用户",type = LogType.UPDATE)
    public Result changePassword(@RequestBody PasswordDTO passwordDTO) {
        int result = userService.changePassword(passwordDTO);
        if(result<=0){
            return Result.error("修改失败");
        }
        return Result.success("修改成功");
    }
    @ApiOperation("忘记密码")
    @AuthAccess
    @PostMapping("/forgetPassword")
    @HoneyLogs(operation = "用户",type = LogType.UPDATE)
    public Result forgetPassword(@RequestBody ForgetDTO forgetDTO) {
        int result = userService.forgetPassword(forgetDTO);
        if(result<=0){
            return Result.error("提交失败");
        }
        return Result.success("提交成功");
    }
    @ApiOperation("用户分页查询")
    @PostMapping("/page")
    public Result page(@RequestBody UserPageDTO userPageDTO) {
//        UserVo vo = userService.page(userPageDTO);
        Page<UserVo> page = userService.page(userPageDTO);
        if (page==null){
            return Result.error("查询失败");
        }
        return Result.success(page);
    }
    @ApiOperation("数据全部导出")
//    @AuthAccess
    @GetMapping("/export")
    public void export( HttpServletResponse response)throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<UserVo> list = userService.export();
        if (list==null){
            throw new ServiceException(ErrorCode.SYSTEM_ERROR);
        }
        List<UserVo> vo = list.stream()
                .peek(user -> {
                    // 替换 username 为 "未知"
//                    if (user.getUsername() == null) {
//                        user.setUsername("未知");
//                    }
                    // 替换 gender 为 "男"、"女" 或 "未知"
                    if (user.getGender() == null) {
                        user.setGender("未知");
                    } else if ("1".equals(user.getGender())) {
                        user.setGender("男");
                    } else if ("0".equals(user.getGender())) {
                        user.setGender("女");
                    }
                })
                .collect(Collectors.toList());


        writer.write(vo, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("用户信息表", "UTF-8") + ".xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream, true);
        writer.close();
        outputStream.flush();
        outputStream.close();
    }
    @ApiOperation("数据批量导入")
    @PostMapping("/import")
    public Result importData(MultipartFile file) throws IOException {
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<User> userList = reader.readAll(User.class);
        // 写入数据到数据库
        try {
            userService.saveBatch(userList);
        } catch (Exception e) {
//            e.printStackTrace();
            return Result.error("数据批量导入错误");
        }
        return Result.success();
    }
}
